<?php
/**
 * Created by PhpStorm.
 * User: yzh
 * Date: 2019/5/10
 * Time: 16:11
 */

namespace app\api\service;


use app\api\model\PosterClass;
use  app\api\model\Poster as PosterModel;
use app\api\model\PosterMaterial;
use  app\api\model\ThirdApp;
use app\lib\exception\MiniSuiteException;
use think\Db;

class Poster
{

    /**
     * 获取素材
     * @return false|\PDOStatement|string|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getMaterial(){
        $material = PosterClass::getClass();
        $data = $material->toArray();
        foreach ( $data as $key=>$item){
            $data[$key]['poster'] = array_slice($item['poster'],0,3);
        }
        return $data;
    }

    /**
     * 获取素材列表
     * @param $style
     * @return array|false|\PDOStatement|string|\think\Model
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getMaterialByClass($style,$size,$page){
        $materials = PosterMaterial::getPosterByClass($style,$size,$page);
        return $materials;
    }

    /**
     * 获取每日推荐海报
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getRecommendPoster(){
        $data = PosterMaterial::getPosterID();
        $ids =  $data->column('id');
        shuffle($ids);
        $list = array_slice($ids,0,4);
        $poster = PosterMaterial::getPosterByIds($list);
        return $poster;
    }

    /**
     * 获取海报二维码
     * @param $t_id 管理员id
     * @param $wu_id 名片所有人id
     * @param $m_id 素材id
     * @param $style 类型
     * @param $path 扫码跳页路径
     * @param $words 海报类容
     * @return mixed
     * @throws MiniSuiteException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getQRCode($t_id,$wu_id,$m_id,$style,$path,$words){
        $poster = PosterModel::getPoster($wu_id,$m_id);
        //已有名片直接返回
        if ($m_id != 0){
            if (!empty($poster)){
                $status['id'] = $poster->id;
                $status['key'] = config('setting.remote_img_url').$poster->qr_code;
                return $status;
            }
        }
        //插入数据
        $posterData['m_id'] = $m_id;
        $posterData['t_id'] = $t_id;
        $posterData['wu_id'] = $wu_id;
        $posterData['source'] = 1;
        $posterData['style'] = $style;
        $posterData['goods_id'] =  isset($words['goods_id'])?$words['goods_id'] : 0;
        //创建海报信息
        $posterInfo = PosterModel::createPoster($posterData);
        //获取名片码
        $scene = 'sowcode_'.$wu_id.'&'.'p_'.$posterInfo->id;
        $page = $path;
        list($data, $path, $name, $result) = $this->getQRCodeImg( $t_id,$wu_id,$scene,$page);
        if ($data != null || !$result){
            throw new MiniSuiteException([
                'code'=>'201',
                'msg'=>'获取二维码'.$data->errmsg,
                'error_code'=>$data->errcode
            ]);
        }else{
            $update['qr_code'] = $result['key'];
            $update['page'] = $page;
            $update['scene'] = $scene;
            $update['word'] = isset($words['word'])?$words['word'] : '';
            $update['eject'] =isset($words['eject'])?$words['eject'] : '';
            PosterModel::updatePoster($posterInfo->id,$update);
            $status['id'] = $posterInfo->id;
            $status['key'] = config('setting.remote_img_url').$result['key'];
            return $status;
        }
    }

    /**
     * @param $t_id
     * @param $scene
     * @param $page
     * @return array
     * @throws \Exception
     */
    public function getQRCodeImg($t_id,$wu_id,$scene,$page): array
    {
        $access_token = $this->getAcessToken($t_id);
        $url = 'https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=%s';
        $url = sprintf($url, $access_token);
        $params = [
            "scene" =>$scene,
            "page" => $page,
        ];
        $requestData = curl_post($url, $params);
        $data = json_decode($requestData);
        $path = $this->createFolder();
        $name = md5(time() + rand(0, 1000));
        $result = file_put_contents($path . '/' . $name . '.jpg', $requestData, true);
        if ($result){
            $uplode = new FileUpload();//7牛云上传
            $result =  $uplode->uploadFile(ltrim($path.'/'.$name.'.jpg', "."),$path . '/' . $name . '.jpg',$wu_id);
        }
        return array($data, $path, $name, $result);
    }

    /**
     * 添加海报
     * @param $id
     * @return mixed
     * @throws MiniSuiteException
     */
    public function addPoster($id,$poster_id){
        $update['url'] =$poster_id;
        $result=  PosterModel::updatePoster($id,$update);
        return $result;
    }

    /**
     * 获取海报信息
     * @param $id
     * @return PosterModel|null
     * @throws \think\exception\DbException
     */
    public function getPosterByID($id){
        $result = PosterModel::getPosterById($id);
        return $result;
    }

    /**
     * 获取海报列表
     * @param $wu_id
     * @param $size
     * @param $page
     * @return \think\Paginator
     * @throws \think\exception\DbException
     */
    public function getPosterList($wu_id,$size,$page){
        $result = PosterModel::getPosterList($wu_id,$size,$page);
        return $result;
    }

    /**
     * 获取总用户数
     * @param $wu_id
     * @return false|\PDOStatement|string|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getAllUser($wu_id){
        $result = PosterModel::getAllUser($wu_id);
        if ($result->isEmpty()){
            $allNum = 0;
        }else{
            $list = $result->column('user_count');;
            $allNum = array_sum($list);
        }
        $data['num'] = $allNum;
        return $data;
    }

    /**
     * 获取用户
     * @param $id
     * @return false|\PDOStatement|string|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public  function getUser($id){
        $result = PosterModel::getUser($id);
        return $result;
}




    /**
     * 获取access_token
     * @param $uid
     * @return bool|mixed
     * @throws \app\lib\exception\MiniSuiteException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    private function getAcessToken($uid){
        $info = ThirdApp::getDetailUserInfoByMini($uid);
        $appid = $info->mini->authorizer_appid;
        if (cache($appid)){
            $access_token = json_decode(cache($appid));
        }else{
            $mini = new Mini();
            $access_token =  $mini->getAccessToken($appid);
        }
        return $access_token;
    }

    /**
     * 创建文件夹
     * @return string
     */
    private function createFolder(){
        $data =  date('Ymd',time());
        $path = './qrcode/'.$data;
        if (!is_dir($path)){
            mkdir('./qrcode/'.$data,0777);
        }
        return $path;
    }

}